//
//  Tiezi_pinglun_erji_vc.m
//  ainkjj
//
//  Created by MAX on 2020/5/9.
//  Copyright © 2020 zhiyiLiu. All rights reserved.
//

#import "Tiezi_pinglun_erji_vc.h"


#import "TopicDiscussList_tv_cell.h"
#import "TopicDiscussList.h"



static NSString * const kCellIdentifier = @"TopicDiscussList_tv_cell";

@interface Tiezi_pinglun_erji_vc ()<UITableViewDelegate, UITableViewDataSource, QMUITextViewDelegate>

@property(nonatomic, assign) CGFloat textViewMinimumHeight;

@property (nonatomic, strong)CALayer *separatorLayer2;

@property (nonatomic, strong)UIButton *fabu_btn;


@property (nonatomic, strong)NSMutableArray *dataArr;
@property (nonatomic, assign)int refreshIndex;
@property (nonatomic, assign)NSInteger totalPage;

@property (nonatomic, strong)UIButton *expandBtn;
@property (nonatomic, assign)CGFloat leftPadding;
@property (nonatomic, strong)UIView *text_view_bg;
@end

@implementation Tiezi_pinglun_erji_vc

- (void)initTableView{
    [super initTableView];
    
//    self.title = [NSString stringWithFormat:@"共%ld条评论", self.model.discussNum];
    self.textViewMinimumHeight = 50;
    self.leftPadding = 6;
    
    
    
    self.tableView.backgroundColor = UIColor.whiteColor;
    self.tableView.layer.cornerRadius = 5;
    self.tableView.layer.masksToBounds = YES;
    
    
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    // tableView.separatorColor = UIColor.redColor;
    self.tableView.rowHeight = 92;
    //[tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    self.tableView.mj_header=[MJRefreshNormalHeader  headerWithRefreshingTarget:self refreshingAction:@selector(req)];
    //    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [self.tableView.mj_header beginRefreshing];
    [self.tableView registerNib:[UINib nibWithNibName:@"TopicDiscussList_tv_cell" bundle:nil] forCellReuseIdentifier:@"TopicDiscussList_tv_cell"];
    
    [self.tableView.mj_header beginRefreshing];
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
}
- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
        self.tableView.frame = CGRectMake( 0, 0, ScreenWidth, ScreenHeight - self.textViewMinimumHeight - Lzy_TabbarSafeBottomMargin -30);

    
   
}
- (NSMutableArray *)dataArr{
    if(_dataArr == nil)
    {
        _dataArr = [[NSMutableArray alloc] init];
        
    }
    
    return _dataArr;
}


- (void)req{
    
    
    
    //  请求服务器，获取列表，刷新tv
    self.refreshIndex = 1;
    [self.tableView.mj_footer resetNoMoreData];
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:app_code forKey:@"appCode"];
    [dict setObject:AuthSignin_model.sharedInstance.data.token forKey:@"token"];
    [dict setObject:@(self.typeId).stringValue forKey:@"typeId"];
    [dict setObject:@(self.yiji_pinglun_model.ID).stringValue forKey:@"topPid"];
    [dict setObject:@(self.yiji_pinglun_model.topicId).stringValue forKey:@"topicId"];
    
    [dict setObject:@"1" forKey:@"page"];
    [dict setObject:@"10" forKey:@"pageSize"];
    
    [PPHTTPRequest req:@"java/app/topic/finSonDiscussPaList" parameters:dict success:^(id response) {
        NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
        if ([error_code isEqualToString:@"0"]) {
            TopicDiscussList *model = [TopicDiscussList mj_objectWithKeyValues:response];
            self.title = [NSString stringWithFormat:@"共%ld条评论", model.count];

            if (!model.data || model.data.count == 0) {
                [self showEmptyViewWithImage:UIImageMake(@"notime_img") text:nil detailText:nil buttonTitle:nil buttonAction:NULL];
            }else{
                [self hideEmptyView];
                self.dataArr = model.data.mutableCopy;
                
                //                self.totalPage = model.pages;
            }
            
            
            
            
        }
        else{
            
            
            [QMUITips showError:response[@"error_msg"] ];
            
        }
        [self endMjRefresh];
        
    } failure:^(NSError *error) {
        [self endMjRefresh];
        
        [QMUITips showError:[error localizedDescription] ];
        
    }];
    
    
}
- (void)loadMoreData{
    self.refreshIndex++;
    
    if (self.refreshIndex > self.totalPage) {
        // 拿到当前的上拉刷新控件，变为没有更多数据的状态
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
        
    }else{
        
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:app_code forKey:@"appCode"];
        [dict setObject:AuthSignin_model.sharedInstance.data.token forKey:@"token"];
        [dict setObject:@(self.refreshIndex).stringValue forKey:@"page"];
        [dict setObject:@(self.typeId).stringValue forKey:@"typeId"];
        [dict setObject:@(self.yiji_pinglun_model.ID).stringValue forKey:@"topPid"];
        [dict setObject:@(self.yiji_pinglun_model.topicId).stringValue forKey:@"topicId"];
        
        [dict setObject:@"10" forKey:@"pageSize"];
        
        [PPHTTPRequest req:@"java/app/topic/finSonDiscussPaList" parameters:dict success:^(id response) {
            NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
            if ([error_code isEqualToString:@"0"]) {
                TopicDiscussList *model = [TopicDiscussList mj_objectWithKeyValues:response];
                
                if (!model.data) {
                    [self showEmptyViewWithImage:UIImageMake(@"notime_img") text:nil detailText:nil buttonTitle:nil buttonAction:NULL];
                }else{
                    [self hideEmptyView];
                    [self.dataArr addObjectsFromArray:model.data];
                    
                }
                
                
                
                
            }
            else{
                
                
                [QMUITips showError:response[@"error_msg"] ];
                
            }
            [self endMjRefresh];
            
        } failure:^(NSError *error) {
            [self endMjRefresh];
            
            [QMUITips showError:[error localizedDescription] ];
            
        }];
        
    }
    
}
- (void)endMjRefresh{
    
    dispatch_async(dispatch_get_main_queue(), ^(void) {
        [self.tableView reloadData];
    });
    
    if (self.tableView.mj_footer.isRefreshing) {
        [self.tableView.mj_footer endRefreshing];
    }
    
    
    if (self.tableView.mj_header.isRefreshing) {
        [self.tableView.mj_header endRefreshing];
    }
    
    
}


             // called when 'return' key pressed. return NO to ignore.

- (id<NSCopying>)cachedKeyAtIndexPath:(NSIndexPath *)indexPath {
    TopicDiscussListData *model = self.dataArr[indexPath.row];
    NSString *cacheKey = @"";
    cacheKey = [NSString stringWithFormat:@"%ld",  model.ID];
    
    return cacheKey;
}


#pragma mark - <QMUITableViewDelegate, QMUITableViewDataSource>

- (UITableViewCell *)qmui_tableView:(UITableView *)tableView cellWithIdentifier:(NSString *)identifier {
    if ([identifier isEqualToString:kCellIdentifier]) {
        TopicDiscussList_tv_cell *cell = (TopicDiscussList_tv_cell *)[tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[TopicDiscussList_tv_cell alloc] initForTableView:tableView withReuseIdentifier:identifier];
        }
        cell.separatorInset = UIEdgeInsetsZero;
        return cell;
    }
    
    
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    TopicDiscussListData *model = self.dataArr[indexPath.row];
    QMUITableViewCell *common_cell;
    TopicDiscussList_tv_cell *cell = (TopicDiscussList_tv_cell *)[self qmui_tableView:tableView cellWithIdentifier:kCellIdentifier];
    
    [cell updateCellAppearanceWithIndexPath:indexPath];
    cell.model = model;
    common_cell = cell;
    cell.idxPath = indexPath;
    __weak __typeof(self) weakSelf = self;
    cell.blk = ^(NSIndexPath * _Nonnull idxPath) {
        [weakSelf topicShield:idxPath];
    };
    return common_cell;
}
- (void)topicShield:(NSIndexPath *)indexPath{
    [self.dataArr removeObjectAtIndex:indexPath.row];
    [self.tableView reloadData];
    
}
- (void)adShield:(NSIndexPath *)indexPath{
    
    [self.dataArr removeObjectAtIndex:indexPath.row];
    [self.tableView reloadData];
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    id<NSCopying> cachedKey = [self cachedKeyAtIndexPath:indexPath];
    TopicDiscussListData *model = self.dataArr[indexPath.row];
    
    CGFloat cellH = 60;
    cellH = [tableView qmui_heightForCellWithIdentifier:kCellIdentifier cacheByKey:cachedKey configuration:^(TopicDiscussList_tv_cell *cell) {
        [cell updateCellAppearanceWithIndexPath:indexPath];
        cell.model = model;
    }];
    
    // DLog(@"cachedKey:%@ height:%f",cachedKey, h);
    return cellH;
}


#pragma mark - ================== 评论框相关 ==================
- (void)initSubviews{
    [super initSubviews];
    self.view.backgroundColor = UIColor.groupTableViewBackgroundColor;
    
    self.text_view_bg = [UIView new];
    [self.view addSubview:self.text_view_bg];
    self.text_view_bg.backgroundColor = UIColor.whiteColor;
    self.textView = [[QMUITextView alloc] init];
    self.textView.delegate = self;
    self.textView.placeholder = @"请输入评论";
    self.textView.placeholderColor = UIColorPlaceholder; // 自定义 placeholder 的颜色
    self.textView.textContainerInset = UIEdgeInsetsMake(0, 0, 10, 7);
    //    self.textView.returnKeyType = UIReturnKeySend;
    //    self.textView.enablesReturnKeyAutomatically = YES;
    self.textView.typingAttributes = @{NSFontAttributeName: UIFontMake(15),
                                       NSParagraphStyleAttributeName: [NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight:20],
                                       NSForegroundColorAttributeName: self.textView.textColor
    };
    self.textView.backgroundColor = UIColor.qd_backgroundColorLighten;
    // 限制可输入的字符长度
    self.textView.maximumTextLength = 5000;
    
    
    // 限制输入框自增高的最大高度
    self.textView.maximumHeight = 200;
    
    //    self.textView.layer.borderWidth = PixelOne;
    //    self.textView.layer.borderColor = UIColorSeparator.CGColor;
    //    self.textView.layer.cornerRadius = 4;
    [self.view addSubview:self.textView];
    
    
    
    UILabel *lb = [[UILabel alloc] init];
    [self.view addSubview:lb];
    self.beihuifuren_lb = lb;
    lb.textColor = UIColor.darkGrayColor;
    lb.font = [UIFont systemFontOfSize:14];
    lb.backgroundColor = UIColor.whiteColor;
    self.beihuifuren_lb.text = [NSString stringWithFormat:@"评论给%@", self.yiji_pinglun_model.discussNikeName];
    self.huifuId = self.yiji_pinglun_model.ID;

    //    self.beihuifuren_lb.hidden = YES;
    
    
    
    self.separatorLayer2 = [CALayer qmui_separatorLayer];
    [self.view.layer addSublayer:self.separatorLayer2];
    
    
    
    
    UIButton *expandBtn = [[UIButton alloc] init];
    self.expandBtn = expandBtn;
    expandBtn.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:expandBtn];
    [expandBtn addTarget:self action:@selector(expand) forControlEvents:UIControlEventTouchUpInside];
    [expandBtn setTitleColor:rgb(91,132,227) forState:UIControlStateNormal];
    [expandBtn setImage:UIImageMake(@"unwind_icon") forState:UIControlStateNormal];
    [expandBtn setImage:UIImageMake(@"shrink_icon") forState:UIControlStateSelected];
    
    
    UIButton *btn = [[UIButton alloc] init];
    [self.view addSubview:btn];
    self.fabu_btn = btn;
    [btn setTitle:@"发布" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(fabu_action) forControlEvents:UIControlEventTouchUpInside];
    [btn setTitleColor:rgb(91,132,227) forState:UIControlStateNormal];
    
    [self updateCommentViewHeight:self.textViewMinimumHeight width:ScreenWidth -  self.leftPadding - 60];
    
    
    self.beihuifuren_lb.hidden = YES;
    self.expandBtn.hidden = YES;
    self.separatorLayer2.hidden = YES;
}

-(void)fabu_action{
    
    QMUITextView *tv = self.textView;
    if (tv.text.length == 0) {
        return;
    }
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:app_code forKey:@"appCode"];
    [dict setObject:AuthSignin_model.sharedInstance.data.token forKey:@"token"];
    [dict setObject:@(self.yiji_pinglun_model.topicId).stringValue forKey:@"topicId"];
    [dict setObject:tv.text forKey:@"content"];
    
    [dict setObject:@(self.huifuId).stringValue forKey:@"pid"];
    
    //sender.userInteractionEnabled = NO;
    __block QMUITips *qmui_tip = [QMUITips showLoading:@"提交中..." inView:self.navigationController.view];
    
    [PPHTTPRequest req:@"java/app/topic/pubDiscuss" parameters:dict success:^(id response) {
        NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
        if ([error_code isEqualToString:@"0"]) {
//            self.model.discussNum +=1;
            
            tv.text = @"";
            [qmui_tip showSucceed:@"评论成功" hideAfterDelay:2];
            [self.tableView.mj_header beginRefreshing];
        }
        else{
            
            
            [qmui_tip showError:response[@"error_msg"] hideAfterDelay:2];
            
        }
        self.textView.text = nil;
    } failure:^(NSError *error) {
        [qmui_tip showError:[error localizedDescription] hideAfterDelay:2];
        
    }];
    
    [self.view endEditing:YES];
}

-(void)expand{
    if (self.expandBtn.selected) {
        [UIView animateWithDuration:0.3 animations:^{
            CGSize textViewSize = [self.textView sizeThatFits:CGSizeMake(ScreenWidth -  self.leftPadding - 60, CGFLOAT_MAX)];
            [self updateCommentViewHeight:textViewSize.height width:ScreenWidth -  self.leftPadding - 60];
            
        }];
    }else{
        [UIView animateWithDuration:0.3 animations:^{
            
            [self updateCommentViewHeight:self.textView.maximumHeight width:ScreenWidth -  self.leftPadding - 60];
            
        }];
    }
    self.expandBtn.selected = !self.expandBtn.selected;
    
}

#pragma mark - <QMUITextViewDelegate>

- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
    [self updateCommentViewHeight:self.textViewMinimumHeight width:ScreenWidth -  self.leftPadding - 60];
    self.beihuifuren_lb.hidden = YES;
    self.expandBtn.hidden = YES;
    self.separatorLayer2.hidden = YES;
    self.beihuifuren_lb.text = [NSString stringWithFormat:@"评论给%@", self.yiji_pinglun_model.discussNikeName];
    textView.text = nil;
    
    return YES;
}
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    self.beihuifuren_lb.hidden = NO;
    self.expandBtn.hidden = NO;
    self.separatorLayer2.hidden = NO;
    CGSize textViewSize = [self.textView sizeThatFits:CGSizeMake(ScreenWidth -  self.leftPadding - 60, CGFLOAT_MAX)];
    [self updateCommentViewHeight:textViewSize.height width:ScreenWidth -  self.leftPadding - 60];
    return YES;
}

// 实现这个 delegate 方法就可以实现自增高
- (void)textView:(QMUITextView *)textView newHeightAfterTextChanged:(CGFloat)height {
    
    if (self.expandBtn.selected) {
        return;
    }
    height = fmax(height, self.textViewMinimumHeight);
    BOOL needsChangeHeight = CGRectGetHeight(textView.frame) != height;
    if (needsChangeHeight) {
        CGSize textViewSize = [self.textView sizeThatFits:CGSizeMake(ScreenWidth - self.leftPadding - 60, CGFLOAT_MAX)];
        
        [self updateCommentViewHeight:textViewSize.height width:ScreenWidth -  self.leftPadding - 60];
    }
}

- (void)updateCommentViewHeight:(CGFloat)heigt width:(CGFloat)width{
    self.textView.frame = CGRectMake(self.leftPadding, ScreenHeight - heigt - Lzy_TabbarSafeBottomMargin ,  width, fmax(heigt, self.textViewMinimumHeight));
    self.text_view_bg.frame = CGRectMake(0, CGRectGetMinY(self.textView.frame) - 30, ScreenWidth, fmax(heigt, self.textViewMinimumHeight));
    
    [self update_xiangguan];
    
}

- (void)update_xiangguan{
    self.beihuifuren_lb.frame = CGRectMake( 10, CGRectGetMinY(self.textView.frame) - 30, ScreenWidth - 60, 20);
    self.separatorLayer2.frame =  CGRectFlatMake(0, CGRectGetMinY(self.beihuifuren_lb.frame) , CGRectGetWidth(self.view.bounds), PixelOne);
    self.expandBtn.frame = CGRectMake(CGRectGetMaxX(self.beihuifuren_lb.frame), CGRectGetMinY(self.separatorLayer2.frame)  , 60, 30);
    self.fabu_btn.frame = CGRectMake(CGRectGetMaxX(self.textView.frame), CGRectGetMaxY(self.textView.frame) - 30, ScreenWidth - CGRectGetMaxX(self.textView.frame), 30);
}

- (void)textView:(QMUITextView *)textView didPreventTextChangeInRange:(NSRange)range replacementText:(NSString *)replacementText {
    //    [QMUITips showWithText:[NSString stringWithFormat:@"文字不能超过 %@ 个字符", @(textView.maximumTextLength)] inView:self.view hideAfterDelay:.8];
}

// 可以利用这个 delegate 来监听发送按钮的事件，当然，如果你习惯以前的方式的话，也可以继续在 textView:shouldChangeTextInRange:replacementText: 里处理
- (BOOL)textViewShouldReturn:(QMUITextView *)textView {
    
    [self fabu_action];
    // return YES 表示这次 return 按钮的点击是为了触发“发送”，而不是为了输入一个换行符
    return YES;
}
@end

